package com.tianqingwl.gsystem.install.filter;

import com.tianqingwl.gsystem.install.pojo.InstallStatus;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class InstallFilter extends OncePerRequestFilter {

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        boolean install = InstallStatus.isInstall();
        String requestURI = request.getRequestURI();
        //放行静态资源
        if (requestURI.startsWith("/layuimini")||requestURI.indexOf("favicon.ico")>-1){
            filterChain.doFilter(request, response);
            return;
        }
        //已安装且访问安装页
        if (install && requestURI.indexOf("install") > -1) {
            response.sendRedirect(request.getContextPath() + "/");
            return;
        }
        Cookie[] cookies = request.getCookies();
        //安装页
        if (!install && requestURI.indexOf("install")>-1){
            if (cookies != null) {
                for (int i = 0; i < cookies.length; i++) {
                    cookies[i].setMaxAge(0);
                    response.addCookie( cookies[i]);
                    cookies[i]=new Cookie(cookies[i].getName(),null);
                }
            }
        }
        //未安装且不是安装页
        if (!install && requestURI.indexOf("install") == -1) {
            if (cookies != null) {
                for (int i = 0; i < cookies.length; i++) {
                    cookies[i].setMaxAge(0);
                    response.addCookie( cookies[i]);
                    cookies[i]=new Cookie(cookies[i].getName(),null);
                }
            }

            response.sendRedirect(request.getContextPath() + "/install");
            return;
        }
        filterChain.doFilter(request, response);
    }
}
